package com.nightwalkbuddy.ui;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class SettingsActivity extends Activity {

	private static final String MY_GPS = " and my GPS location: ";
	private static final String ALARM_ACTIVATED = "Alarm has been activated";
	private static final int CAR_ALARM = R.raw.alarm;
	private static final int NUCLEAR_ALARM = R.raw.nuclear;
	private static final int SMOKE_ALARM = R.raw.smoke;

	// for SMS message
	private static final String SMS_NOT_DELIVERED = "SMS not delivered";
	private static final String SMS_DELIVERED = "SMS delivered";
	private static final String RADIO_OFF = "Radio off";
	private static final String NULL_PDU = "Null PDU";
	private static final String NO_SERVICE = "No service";
	private static final String GENERIC_FAILURE = "Generic failure";
	private static final String SMS_SENT = "SMS sent";
	private static final String SENT = "TEXT_SENT";
	private static final String DELIVERED = "TEXT_DELIVERED";

	private String aMessage = "";
	private String aPhoneNr = "";
	private String aUserName = "";
	private double latLoc;
	private double longLoc;
	private Button btn_Settings_Emg;
	private Button btn_Test;
	private Spinner spinner;
	private int alarm_selected;
	private int spinnerPosition;
	private MediaPlayer mp;
	//private MenuActivity menuactivity = new MenuActivity();

	// SMS broadcast
	private BroadcastReceiver brSent = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			switch (getResultCode()) {
			case Activity.RESULT_OK:
				popup(SMS_SENT);
				break;
			case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
				popup(GENERIC_FAILURE);
				break;
			case SmsManager.RESULT_ERROR_NO_SERVICE:
				popup(NO_SERVICE);
				break;
			case SmsManager.RESULT_ERROR_NULL_PDU:
				popup(NULL_PDU);
				break;
			case SmsManager.RESULT_ERROR_RADIO_OFF:
				popup(RADIO_OFF);
				break;
			}
		}

	};

	private BroadcastReceiver brDelivered = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			switch (getResultCode()) {
			case Activity.RESULT_OK:
				popup(SMS_DELIVERED);
				break;
			case Activity.RESULT_CANCELED:
				popup(SMS_NOT_DELIVERED);
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		initComponents();
		Bundle bundle = new Bundle();
		Intent sender = getIntent();
		bundle = sender.getExtras();

		spinnerPosition = bundle.getInt("spinnerPosition");
		alarm_selected = bundle.getInt("alarm_selected");
		aMessage = bundle.getString("aMessage");
		aPhoneNr = bundle.getString("aPhoneNr");
		aUserName = bundle.getString("aUserName");
		//latLoc = menuactivity.getLat();
		//longLoc = menuactivity.getLong();
		latLoc = Double.parseDouble(bundle.getString("lat"));
		longLoc = Double.parseDouble(bundle.getString("long"));
		
		registerReceiver(brSent, new IntentFilter(SENT));
		registerReceiver(brDelivered, new IntentFilter(DELIVERED));
	}

	/**
	 * During onPause unregistered receivers
	 */
	protected void onPause() {
		super.onPause();
		unregisterReceiver(brSent);
		unregisterReceiver(brDelivered);
	}

	/**
	 * During onResume register receivers
	 */
	protected void onResume() {
		super.onResume();
		registerReceiver(brSent, new IntentFilter(SENT));
		registerReceiver(brDelivered, new IntentFilter(DELIVERED));
		spinner.setSelection(spinnerPosition);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_settings, menu);
		return true;
	}

	/**
	 * Options menu selection
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handles item selection
		switch (item.getItemId()) {
		case R.id.activity_settings_Logout:
			menuLogout();
			return (true);
		case R.id.activity_settings_MainMenu:
			returnToMain();
			return (true);
		default:
			return (super.onOptionsItemSelected(item));
		}

	}

	/**
	 * if MediaPlayer is playing then stop.
	 */
	private void checkPlayer() {
		if (mp != null) {
			mp.stop();
		}
	}

	/**
	 * return to mainMenu click
	 */
	private void returnToMain() {
		Intent intent = (new Intent(this, MenuActivity.class));
		intent.putExtra(getString(R.string.app_name), true);
		intent.putExtra("spinnerPosition", spinnerPosition);
		intent.putExtra("alarm_selected", alarm_selected);
		intent.putExtra("aUserName", this.aUserName);
		intent.putExtra("aMessage", this.aMessage);
		intent.putExtra("aPhoneNr", this.aPhoneNr);
		
		//passing extra back to Main menu
		intent.putExtra("lat", String.valueOf(latLoc));
		intent.putExtra("long", String.valueOf(longLoc));
		intent.putExtra("sender", getString(R.string.title_activity_settings));
		
		checkPlayer();
		startActivity(intent);
	}

	/**
	 * menu logout click
	 */
	private void menuLogout() {
		popup(getString(R.string.goodbye_msg));
		startActivity(new Intent(SettingsActivity.this, LoginActivity.class));
		finish();
	}

	// method to pop up Toast message
	protected void popup(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	/**
	 * Send emergency text message to emergency contact
	 * 
	 * @param phoneNumber
	 * @param message
	 */
	private void sendSMS(String phoneNumber, String message) {
		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
				SENT), 0);
		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
				new Intent(DELIVERED), 0);

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);

	}

	/**
	 * initialize the view components The logout button has Toast message prior
	 * to logging out the user
	 */

	protected void initComponents() {
		btn_Settings_Emg = (Button) findViewById(R.id.btn_Settings_Emg);
		btn_Test = (Button) findViewById(R.id.btn_TestSound);
		spinner = (Spinner) findViewById(R.id.spinner_settings);
		spinner.setSelection(spinnerPosition);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long id) {
				// TODO Auto-generated method stub

				spinner.getItemAtPosition(position);
				if (position != spinnerPosition) {
					switch (position) {
					case 0:
						alarm_selected = CAR_ALARM;
						spinnerPosition = (position);

						break;
					case 1:
						alarm_selected = NUCLEAR_ALARM;
						spinnerPosition = (position);
						break;
					case 2:
						alarm_selected = SMOKE_ALARM;
						spinnerPosition = (position);
						break;
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});
		// setting array adaptors to spinners
		// ArrayAdapter is a BaseAdapter that is backed by an array of arbitrary
		// objects
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.spinner_settings_entries,
				android.R.layout.simple_spinner_dropdown_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setSelection(spinnerPosition);
		btn_Test.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				checkPlayer();
				mp = MediaPlayer.create(getBaseContext(), alarm_selected);
				mp.start();

			}

		});

		/**
		 * button to start alarm that works like a panic button It also sends
		 * SMS text message to emergency contact for help
		 */
		btn_Settings_Emg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//latLoc = menuactivity.getLat();
				//longLoc = menuactivity.getLong();
				String emMsg = aMessage + MY_GPS + latLoc + ", " + longLoc;
				popup(ALARM_ACTIVATED);
				checkPlayer();
				mp = MediaPlayer.create(getBaseContext(), alarm_selected);
				mp.start();
				sendSMS(aPhoneNr, emMsg);
			}
		});

	}

}
